package cn.itsource.product.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.product.domain.Product;
import cn.itsource.product.domain.ProductDetail;
import cn.itsource.product.mapper.ProductDetailMapper;
import cn.itsource.product.mapper.ProductMapper;
import cn.itsource.product.service.IProductService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {
    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Autowired
    private ProductMapper productMapper;
    @Override
    @Transactional
    public void remove(Long productId) {
        //1.通过服务Id 删除服务详情
        productDetailMapper.deleteByProductId(productId);
        productMapper.delete(productId);
    }

    @Override
    public void add(Product product) {
        productMapper.save(product);//需要返回主键
        ProductDetail detail = product.getDetail();
        if(detail != null){
            detail.setProduct_id(product.getId());
            productDetailMapper.save(detail);
        }
    }

    @Override
    public void update(Product product) {
        productMapper.update(product);
        ProductDetail detail = product.getDetail();
        if(detail != null){
            detail.setProduct_id(product.getId());
            if(detail.getId() != null){
                productDetailMapper.update(detail);
            }else{
                productDetailMapper.save(detail);
            }

        }

    }

    @Override
    public ProductDetail findDetailByProductId(Long productId) {
        return productDetailMapper.loadByProductId(productId);
    }
    
    // 上架或者下架业务方法
    @Override
    public void onOrOffsale(int i, List<Long> ids) {
        // 根据传入状态码 0为上架 1为下架 进行判断并业务处理
        if (i == 1 ) { // 上架
            // 上架需要两个数据 上架时间 上架商品
            // 新建一个map，用来存放这两个数据
            HashMap<String, Object> params  = new HashMap<>();
            params.put("onsaleTime",new Date());
            params.put("ids",ids);
            productMapper.onsale(params);
        } else {
            // 新建一个map，用来存放这两个数据
            HashMap<String, Object> params  = new HashMap<>();
            params.put("offsaleTime",new Date());
            params.put("ids",ids);
            productMapper.offsale(params);
        }
        
    }
}
